#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QTcpSocket * socket,QMainWindow *parent) :
     QMainWindow(parent),ui(new Ui::MainWindow)
    ,my_socket(socket)
{

    this->setMinimumSize(1200, 900);
    SetUi();
    setupConnections();

}
void MainWindow::SetUi()
{
    // 创建中央部件
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // 创建顶部标题
    titleLabel = new QLabel("快递分拣系统", this);
    QFont titleFont;
    titleFont.setPointSize(26);
    titleFont.setBold(true);
    titleFont.setFamily("Microsoft YaHei");
    titleLabel->setFont(titleFont);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("QLabel { "
                             "color: white; "
                             "background-color: #2980b9; "
                             "padding: 19px; "
                             "margin: 0px; "
                             "border: none; "
                             "}");

    // 创建内容区域布局
    QHBoxLayout *contentLayout = new QHBoxLayout();

    // 左边按钮布局
    QVBoxLayout *leftLayout = new QVBoxLayout();
    button1 = new QPushButton("普通仓库", this);
    button2 = new QPushButton("紧急仓库", this);
    button3 = new QPushButton("专用仓库", this);
    button4 = new QPushButton("所有", this);

    // 设置按钮样式
    QString buttonStyle = "QPushButton { "
                         "background-color: #34495e; "
                         "color: white; "
                         "border: none; "
                         "padding: 15px; "
                         "margin: 5px; "
                         "border-radius: 5px; "
                         "font-size: 19px; "
                         "}"
                         "QPushButton:hover { "
                         "background-color: #2c3e50; "
                         "}";

    button1->setStyleSheet(buttonStyle);
    button2->setStyleSheet(buttonStyle);
    button3->setStyleSheet(buttonStyle);
    button4->setStyleSheet(buttonStyle);

    button1->setFixedHeight(60);
    button2->setFixedHeight(60);
    button3->setFixedHeight(60);
    button4->setFixedHeight(60);

    leftLayout->addWidget(button1);
    leftLayout->addWidget(button2);
    leftLayout->addWidget(button3);
    leftLayout->addWidget(button4);
    leftLayout->addStretch();
    leftLayout->setSpacing(10);

    // 右边布局
    QVBoxLayout *rightLayout = new QVBoxLayout();

    // 搜索区域
    QHBoxLayout *searchLayout = new QHBoxLayout();
    searchLineEdit = new QLineEdit(this);
    searchButton = new QPushButton("搜索", this);

    searchLineEdit->setPlaceholderText("请输入快递单号或关键词...");
    searchLineEdit->setStyleSheet("QLineEdit { "
                                 "padding: 10px; "
                                 "border: 2px solid #bdc3c7; "
                                 "border-radius: 5px; "
                                 "font-size: 19px; "
                                 "}"
                                 "QLineEdit:focus {"
                                 "border: 2px solid #3498db; "
                                 "background-color: #f8f9fa; "
                                 "}");

    searchButton->setStyleSheet(buttonStyle);
    searchButton->setFixedWidth(80);

    searchLayout->addWidget(searchLineEdit);
    searchLayout->addWidget(searchButton);

    // 设置表格
    tableWidget = new QTableWidget(this);
    tableWidget->setColumnCount(4); // 设置4列：快递单号、路线、类型、仓库
    tableWidget->setHorizontalHeaderLabels(QStringList() << "快递单号" << "路线" << "快递类型" << "仓库");

    // 设置表格样式
    tableWidget->setStyleSheet("QTableWidget { "
                              "background-color: white; "
                              "border: 2px solid #ecf0f1; "
                              "border-radius: 5px; "
                              "gridline-color: #bdc3c7; "
                              "font-size: 16px; "
                              "}"
                              "QTableWidget::item { "
                              "padding: 8px; "
                              "border-bottom: 1px solid #ecf0f1; "
                              "}"
                              "QTableWidget::item:selected { "
                              "background-color: #e3f2fd; "
                              "color: black; "
                              "}"
                              "QHeaderView::section { "
                              "background-color: #34495e; "
                              "color: white; "
                              "padding: 10px; "
                              "border: none; "
                              "font-size: 16px; "
                              "font-weight: bold; "
                              "}");

    // 设置表格属性
    tableWidget->setAlternatingRowColors(true); // 交替行颜色
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); // 整行选择
    tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); // 单行选择
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); // 不可编辑
    tableWidget->horizontalHeader()->setStretchLastSection(true); // 最后一列拉伸
    tableWidget->verticalHeader()->setVisible(false); // 隐藏行号
    tableWidget->setSortingEnabled(true); // 启用排序

    // 设置列宽比例
    tableWidget->setColumnWidth(0, 200); // 快递单号列宽
    tableWidget->setColumnWidth(1, 300); // 路线列宽
    tableWidget->setColumnWidth(2, 150); // 类型列宽
    // 仓库列自动拉伸

    rightLayout->addLayout(searchLayout);
    rightLayout->addWidget(tableWidget); // 添加表格到布局

    // 组合布局
    contentLayout->addLayout(leftLayout, 1);
    contentLayout->addLayout(rightLayout, 3);
    contentLayout->setSpacing(20);

    mainLayout->addWidget(titleLabel);
    mainLayout->addLayout(contentLayout);
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);

}

void MainWindow::addTableRow(const QString &trackingNumber,
                           const QString &route,
                           const QString &type,
                           const QString &warehouse)
{

    int row=tableWidget->rowCount();
    tableWidget->insertRow(row);

    // 创建表格项
    QTableWidgetItem *item1 = new QTableWidgetItem(trackingNumber);
    QTableWidgetItem *item2 = new QTableWidgetItem(route);
    QTableWidgetItem *item3 = new QTableWidgetItem(type);
    QTableWidgetItem *item4 = new QTableWidgetItem(warehouse);

    // 设置项属性
    item1->setTextAlignment(Qt::AlignCenter);
    item2->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    item3->setTextAlignment(Qt::AlignCenter);
    item4->setTextAlignment(Qt::AlignCenter);

    // 根据仓库类型设置颜色
    if (warehouse == "紧急仓库") {
        item4->setBackground(QColor(255, 230, 230)); // 浅红色背景
        item4->setForeground(QColor(192, 0, 0));     // 红色文字
    } else if (warehouse == "专用仓库") {
       item4->setBackground(QColor(230, 230, 255)); // 浅蓝色背景
       item4->setForeground(Qt::blue);//蓝色文字
    }

    // 添加到表格
    tableWidget->setItem(row, 0, item1);
    tableWidget->setItem(row, 1, item2);
    tableWidget->setItem(row, 2, item3);
    tableWidget->setItem(row, 3, item4);
}

  void MainWindow::setupConnections()
  {
      // 连接UI信号槽
      connect(searchButton, &QPushButton::clicked, this, &MainWindow::onSearchClicked);
      connect(button1, &QPushButton::clicked, this, &MainWindow::onButton1Clicked);
      connect(button2, &QPushButton::clicked, this, &MainWindow::onButton2Clicked);
      connect(button3, &QPushButton::clicked, this, &MainWindow::onButton3Clicked);
      connect(button4, &QPushButton::clicked, this, &MainWindow::onButton4Clicked);
      connect(searchLineEdit, &QLineEdit::returnPressed, this, &MainWindow::onSearchClicked);

  }
   void MainWindow::onSearchClicked()
   {
       soket_statue();
       qDebug()<<"start";
       QString searchText = searchLineEdit->text();
       QString quotedStr = "'" + searchText + "'";
       QByteArray byteArray = searchText.toUtf8();
       const char *id = byteArray.constData();

       if (!searchText.isEmpty()) {
             my_socket->write("Q");
       }else{
         qWarning()<<"搜索内容不能为空";
       }

       my_socket->write(id);
       display();
       qDebug()<<"searchCliked:"<<searchText;
   }

   void MainWindow::soket_statue()
   {
       if (!my_socket || !my_socket->isOpen()) {
              textEdit->append("错误: 套接字未连接");
              return;
          }
          if (my_socket->state() != QAbstractSocket::ConnectedState) {
              textEdit->append("错误: 套接字未处于连接状态");
              return;
          }
   }
   void MainWindow::onButton1Clicked()
   {
        soket_statue();
       my_socket->write("A");
         display();

        qDebug()<<"bouton1";
   }
   void MainWindow::onButton4Clicked()
   {
        soket_statue();
       my_socket->write("D");
         display();
        qDebug()<<"bouton4";
   }
   void MainWindow::onButton2Clicked()
   {
       soket_statue();
       my_socket->write("B");

        display();
      qDebug()<<"bouton2";

   }

   void MainWindow::onButton3Clicked()
   {
        my_socket->write("C");
        display();
        qDebug()<<"bouton3";
   }
   void MainWindow::display()
   {
       tableWidget->setRowCount(0);
       TcpDataReceiver recevier(my_socket,this);
       recevier.setReadMode(TcpDataReceiver::ReadUntilDelimiter, QVariant('@'));
       recevier.setTimeout(3000);
       // 读取数据直到遇到 '@' 字符
         QByteArray data = recevier.readData(); // 假设有统一的read方法

         if (!data.isEmpty()) {
             qDebug() << "接收到数据";
         } else {
             qWarning() << "无数据";
         }
          QString receivedData = QString::fromUtf8(data);
         // 按行分割
         QStringList lines = receivedData.split('\n', Qt::SkipEmptyParts);
         QStringList processedLines;

         for (const QString &line : lines) {
             QString processedLine = line;
             // 只替换每行末尾的 A
             if (line.endsWith("A")) {
                 processedLine = line.left(line.length() - 1) + "普通件";
             }else if (line.endsWith("B")) {
                 processedLine = line.left(line.length() - 1) + "紧急件";
             }else if (line.endsWith("C")) {
                 processedLine = line.left(line.length() - 1) + "特殊件";
             }
             processedLines.append(processedLine);
         }
         QString result = processedLines.join('\n');
       qDebug()<<result;
       processPackageData(result);

   }
//   void MainWindow::processPackageData(const QString &rawData)
//   {
//       // 按行分割数据
//       QStringList lines = rawData.split('\n', Qt::SkipEmptyParts);

//       for (const QString &line : lines) {
//           // 去除首尾空白
//           QString trimmedLine = line.trimmed();
//           if (trimmedLine.isEmpty()) continue;

//           // 按逗号分割字段
//           QStringList fields = trimmedLine.split(',', Qt::SkipEmptyParts);
//           if (fields.size() < 3) {
//               qDebug() << "Invalid data format:" << trimmedLine;
//               continue;
//           }
//           // 提取和清理各个字段
//           QString trackingNumber = fields[0].trimmed();
//           QString route = processRoute(fields[1].trimmed()); // 处理路线格式
//           QString typeAndWarehouse = fields[2].trimmed();

//           // 分离类型和仓库（假设格式为"类型件"）
//           QString type, warehouse;
//           if (typeAndWarehouse.endsWith("件")) {
//               type = typeAndWarehouse;
//               // 根据类型确定仓库
//               if (typeAndWarehouse == "紧急件") {
//                   warehouse = "紧急仓库";
//               } else if (typeAndWarehouse == "特殊件") {
//                   warehouse = "专用仓库";
//               } else {
//                   warehouse = "普通仓库";
//               }
//           } else {
//               // 如果格式不匹配，使用默认值
//               type = typeAndWarehouse;
//               warehouse = "普通仓库";
//           }

//           // 如果有第四个字段，可能是单独的仓库信息
//           if (fields.size() >= 4) {
//               QString possibleWarehouse = fields[3].trimmed();
//               if (!possibleWarehouse.isEmpty()) {
//                   warehouse = possibleWarehouse;
//               }
//           }

//           // 添加到表格
//           addTableRow(trackingNumber, route, type, warehouse);
//       }
//   }

   // 处理路线格式的函数
   QString MainWindow::processRoute(const QString &rawRoute)
   {
       QString route = rawRoute;

       // 替换中文逗号为箭头
       route.replace(" ", " → ");
       // 处理多余的空格
       route = route.simplified();
       // 确保箭头格式统一
       route.replace("->", "→");
       route.replace("- >", "→");
       route.replace(" to ", "→");
       return route;
   }
   void MainWindow::processPackageData(const QString &rawData)
   {
       QStringList lines = rawData.split('\n', Qt::SkipEmptyParts);

       for (const QString &line : lines) {
           QString trimmedLine = line.trimmed();
           if (trimmedLine.isEmpty()) continue;

           // 使用正则表达式匹配更复杂的格式
           QRegularExpression regex("([^,]+),\\s*([^,]+),\\s*([^,]+)(?:,\\s*([^,]+))?");
           QRegularExpressionMatch match = regex.match(trimmedLine);

           if (match.hasMatch()) {
               QString trackingNumber = match.captured(1).trimmed();
               QString rawRoute = match.captured(2).trimmed();
               QString typeInfo = match.captured(3).trimmed();
               QString warehouseInfo = match.captured(4).trimmed(); // 可选的第四个字段

               // 处理路线
               QString route = processRoute(rawRoute);

               // 解析类型和仓库
               QString type, warehouse;
               parseTypeAndWarehouse(typeInfo, warehouseInfo, type, warehouse);

               // 添加到表格
               addTableRow(trackingNumber, route, type, warehouse);
           } else {
               qDebug() << "Failed to parse line:" << trimmedLine;
           }
       }
   }

   void MainWindow::parseTypeAndWarehouse(const QString &typeInfo, const QString &warehouseInfo,
                                        QString &type, QString &warehouse)
   {
       type = typeInfo;

       // 优先使用显式提供的仓库信息
       if (!warehouseInfo.isEmpty()) {
           warehouse = warehouseInfo;
       } else {
           // 根据类型推断仓库
           if (typeInfo.contains("紧急") || typeInfo == "紧急件") {
               warehouse = "紧急仓库";
               type = "紧急件";
           } else if (typeInfo.contains("特殊") || typeInfo == "特殊件") {
               warehouse = "专用仓库";
               type = "特殊件";
           } else {
               warehouse = "普通仓库";
               type = "普通件";
           }
       }
   }
MainWindow::~MainWindow()
{
    delete ui;
}
